<template>
  <view
    class="bg-white rounded-[28rpx] p-[32rpx] shadow-md relative flex flex-col hover:shadow-lg transition-all duration-300"
  >
    <!-- 任务状态标签 -->
    <view class="absolute top-[1rpx] right-[1rpx] bg-[#03a9f4] text-white text-[20rpx] px-[12rpx] py-[4rpx] rounded-[6rpx]">
      {{ change(item) }}
    </view>

    <!-- 头部 -->
    <view class="flex justify-between items-center mb-[18rpx]">
      <view class="text-[32rpx] font-bold text-[#222] flex-1 truncate">{{
        item.taskTitle
      }}</view>
    </view>

    <view
      class="my-[10rpx] p-[18rpx] bg-gradient-to-r from-[#e6f7ff] to-[#bae7ff] rounded-[12rpx] border-l-[6rpx] border-l-[#1890ff]"
    >
      <view class="flex justify-between text-[24rpx] mb-[6rpx] line-clamp-2">
        任务描述：{{ item.desc }}
      </view>
    </view>

    <!-- 核心数据 -->
    <view class="flex items-center mb-[18rpx]">
      <view class="flex items-center">
        <IconFont font-class-name="iconfont" class-prefix="icon" name="rijie" color="#d32f2f" size="20" class="mr-[8rpx]"/>

        <view class="text-[24rpx] font-bold text-[#999]">
          金额：¥{{ Number(item.totalReward).toFixed(2) }}
        </view>
      </view>
      <view class="text-[24rpx] text-[#666]">
      </view>
      <view class="text-[24rpx] text-[#666] ml-auto">截止日期: {{ item.deadline }}</view>
    </view>

    <!-- 底部操作 -->
    <view
      v-if="item.status != 5"
      class="flex items-center justify-end w-full mt-[10rpx] pt-[10rpx] border-t border-[#f5f7fa] gap-[12rpx] flex-wrap"
    >
      <!-- 支付费用按钮 -->
      <nut-button
        size="small"
        type="warning"
        @click.stop="handlePay"
        v-if="item.pay_status === 0"
        class=""
      >
        支付费用
      </nut-button>
      
      <!-- 动态操作按钮 -->
      <template v-for="actionType in availableActions" :key="actionType">
          <nut-button
           :size="getActionConfigLocal(actionType).size || 'small'"
           :type="getActionConfigLocal(actionType).type || 'default'"
           :disabled="getActionConfigLocal(actionType).disabled || false"
           @click.stop="handleAction(actionType)"
           class=""
          >
           {{ getActionConfigLocal(actionType).label }}
         </nut-button>
      </template>

      
      <nut-button
        size="small"
        type="danger"
        disabled
        v-if="item.pay_status == 5"
        class=""
      >
        已取消
      </nut-button>
      <nut-button
        size="small"
        type="danger"
        @click.stop="handleEndTask"
        v-else
        class=""
      >
        取消任务
      </nut-button>

    </view>

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="parseFloat((props.item.total_amount + props.item.release_fee) || '0')"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup>
import { computed, ref } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import { Button as nutButton } from "@nutui/nutui-taro";
import Taro from "@tarojs/taro";
import { post } from "@/utils/request";
import PaymentMethodModal from "@/components/PaymentMethodModal.vue";
import { useUserStore } from "@/store/user";
import { 
  TASK_STATUS, 
  APPLICANT_STATUS, 
  PUBLISHER_STATUS, 
  USER_ROLE,
  getStatusConfig, 
  getAvailableActions, 
  getActionConfig 
} from "@/constants/taskStatus";
import { TaskStatusMap } from "@/utils/dict";

/**
 * 状态转换方法
 * @description 根据任务的不同状态字段显示相应的状态文本
 * @param {Object} item - 任务对象
 * @returns {string} 状态文本
 */
const change = (item) => {
  console.log("item为", item);

  // 根据 item.releaseStatus 显示发布状态，任务类：1 待支付 2 审核中 3 审核通过 4 审核不过 5 已结束
  if (item.releaseStatus) {
    switch (item.releaseStatus) {
      case 1:
        return "待支付";
      case 2:
        return "审核中";
      case 3:
        return "审核通过";
      case 4:
        return "审核不过";
      case 5:
        return "已结束";
      default:
        break;
    }
  }

  // 检查任务是否已取消
  if(item.status == 5){
    return "已取消";
  }
  
  // 检查支付状态
  if(item.pay_status == 0){
    return "未支付";
  }
  
  // 根据任务状态返回对应文本
  switch (item.status) {
    case 1:
      return "招聘中";
    case 2:
      return "停止招聘";
    case 5:
      return "已取消";
    case 4:
      return "已完成";
    case 21:
      return "待审核";
    case 22:
      return "确认完成";
    case 23:
      return "有纠纷";
    case 24:
      return "纠纷协商";
    default:
      return "已发布";
  }
};

const props = defineProps({
  item: {
    type: Object,
    required: true,
    default: () => ({
      id: 0,
      taskTitle: "", // 任务标题
      status: "", // 任务状态
      statusClass: "",
      totalReward: "", // 总赏金
      applyCount: 0, // 报名人数
      desc: "", // 任务描述
      isUrgent: false, // 是否紧急
      pay_status: 0, // 支付状态
      deadline: "", // 截止日期
      releaseStatus: null, // 发布状态：1 待支付 2 审核中 3 审核通过 4 审核不过 5 已结束
      // 新增状态字段
      taskStatus: TASK_STATUS.PAID, // 任务状态
      userRole: USER_ROLE.PUBLISHER, // 用户角色
      userStatus: null, // 用户状态（接单人状态或发布方状态）
    }),
  },
});

// 用户store
const userStore = useUserStore();

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);

const emit = defineEmits([
  "viewDetails", 
  "checkResults", 
  "extendDeadline", 
  "endTask", 
  "viewApplicants",
  // 新增事件
  "cancelTask",
  "selectWinner", 
  "viewProgress",
  "confirmCompletion",
  "raiseDispute",
  "communicatePlatform",
  "acceptSolution",
  "rejectSolution",
  "deleteTask",
  "applyTask",
  "cancelApplication",
  "startTask",
  "abandonTask",
  "submitCompletion",
  "waitConfirmation",
  "refresh"
]);

/**
 * 计算当前状态配置
 */
const currentStatusConfig = computed(() => {
  // 优先使用任务状态
  if (props.item.taskStatus) {
    return getStatusConfig(props.item.taskStatus, 'task');
  }
  // 如果有用户状态，也获取用户状态配置
  if (props.item.userStatus) {
    return getStatusConfig(props.item.userStatus, props.item.userRole === USER_ROLE.PUBLISHER ? 'publisher' : 'applicant');
  }
  return null;
});

/**
 * 获取当前用户可用的操作列表
 */
const availableActions = computed(() => {
  const actions = getAvailableActions(
    props.item.taskStatus || props.item.status,
    props.item.userRole || USER_ROLE.PUBLISHER,
    props.item.userStatus
  );
  console.log("actions==>", actions);
  
  // 当支付状态为1时，添加"查看申请人"按钮
  if (props.item.pay_status === 1) {
    // 检查是否已经包含"查看申请人"操作，避免重复
    if (!actions.includes('view_applicants')) {
      actions.unshift('view_applicants'); // 添加到最前面
    }
  }
  
  console.log("最终actions==>", actions);
  return actions;
});

/**
 * 获取操作按钮配置
 * @param {string} actionType - 操作类型
 * @returns {Object} 按钮配置
 */
const getActionConfigLocal = (actionType) => {
  return getActionConfig(actionType);
};

/**
 * 处理操作按钮点击
 * @param {string} actionType - 操作类型
 */
const handleAction = (actionType) => {
  console.log('执行操作:', actionType, props.item);
  
  // 根据操作类型触发对应事件
  switch (actionType) {
    case 'cancel_task':
      emit('delete', props.item);
      break;
    case 'view_applicants':
      // emit('viewApplicants', props.item);
      Taro.navigateTo({
        url: `/pages/post/applicants?taskId=${props.item.id}&type=task`
      });
      break;
    case 'select_winner':
      emit('selectWinner', props.item);
      break;
    case 'view_progress':
      emit('viewProgress', props.item);
      break;
    case 'confirm_completion':
      emit('confirmCompletion', props.item);
      break;
    case 'raise_dispute':
      emit('raiseDispute', props.item);
      break;
    case 'communicate_platform':
      emit('communicatePlatform', props.item);
      break;
    case 'accept_solution':
      emit('acceptSolution', props.item);
      break;
    case 'reject_solution':
      emit('rejectSolution', props.item);
      break;
    case 'delete_task':
      emit('deleteTask', props.item);
      break;
    case 'apply_task':
      emit('applyTask', props.item);
      break;
    case 'cancel_application':
      emit('cancelApplication', props.item);
      break;
    case 'start_task':
      emit('startTask', props.item);
      break;
    case 'abandon_task':
      emit('abandonTask', props.item);
      break;
    case 'submit_completion':
      emit('submitCompletion', props.item);
      break;
    case 'wait_confirmation':
      emit('waitConfirmation', props.item);
      break;
    default:
      console.warn('未知操作类型:', actionType);
  }
};

// 保留原有的事件处理函数
const handleViewDetails = () => emit("viewDetails", props.item);
const handleCheckResults = () => emit("checkResults", props.item);
const handleExtendDeadline = () => emit("extendDeadline", props.item);
const handleEndTask = () => emit("delete", props.item);

/**
 * 微信支付处理
 * @param {Object} param - 支付参数
 */
const doPay = (param) => {
  window.WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param) {
      if (param.err_msg === "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "购买成功！",
          icon: "success",
          duration: 2000,
        });
      } else {
        Taro.showToast({ title: "购买失败！", icon: "error", duration: 2000 });
      }
      // 支付后刷新页面（2秒后执行，等待提示消失）
      setTimeout(() => {
        // H5环境，也可以用window.location.reload()
        if (process.env.TARO_ENV === 'h5') {
          window.location.reload();
        }
      }, 2000);
    }
  );
};

/**
 * 支付任务费用
 */
const handlePay = () => {
  showPaymentModal.value = true;
};

/**
 * 处理支付确认
 */
const handlePaymentConfirm = async (paymentMethod) => {
  try {
    const deductionBalance = paymentMethod === 'balance' ? 1 : 0;
    const payRes = await post("/pay/task", {
      amount: props.item.total_amount + props.item.release_fee,
      bid: props.item.id,
      vipType: 1,
      deductionBalance: deductionBalance,
    });
    
    if (payRes.code == 0) {
      if (paymentMethod === 'wechat') {
        doPay(payRes.data);
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          userStore.updateBalance();
          // 刷新列表数据
          setTimeout(() => {
            emit('refresh');
          }, 1200);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "error",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: payRes.message || "支付失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("支付失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  // 阻止事件冒泡，避免触发父组件的点击事件
  showPaymentModal.value = false;
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};
</script>